/*封装请求*/
import axios from 'axios'
import store from '@/store'
import router from '@/router/router'
import {getToken, getRefreshToken} from '@/utils/cache'

// const baseUrl = '/api/' //测试
// const baseUrl = 'http://yfgpwebapi.fszyrj.com/schoolBus/' //正式
let baseUrl = process.env.NODE_ENV === 'development' ? process.env.VUE_APP_URL : window.webConfig.webApiBaseUrl;
let ishttps = 'https:' === document.location.protocol;
if(ishttps && /^http:\/\/.*$/.test(baseUrl)){
  baseUrl = baseUrl.replace('http://','https://')
}else if (!ishttps && /^https:\/\/.*$/.test(baseUrl)) {
  baseUrl = baseUrl.replace('https://','http://')
}
//创建实例
const request = axios.create({
  timeout: 60000,
  // baseURL: process.env.VUE_APP_URL
  baseURL: baseUrl
});

//请求拦截
request.interceptors.request.use(
  config => {
    //发送请求前
    config.headers['Authorization'] = `Bearer ${getToken()}`
    return config
  },
  error =>{
    //请求出错
    return Promise.reject(error)
  }
);

//响应拦截
request.interceptors.response.use(
  async res => {
    const status = res.status;
    let data = res.data;
    //未授权
    if (status === 401 || data.errcode === 401){
      await refreshToken();
      exprReqNum--

      //重新请求
      data = await reRequest(res.config)
    }

    let root = data.root;
    if (!root) return res;
    let {errcode,errmsg} = root.response || {},
      {row,total} = root.data || {},
      totalsize = root.page && root.page.totalsize;

    if (errcode != 0){
      ElMessage({
        message: errmsg,
        type: 'error',
        // showClose: true,
        // offset: 50
      });
    }
    return {total:totalsize || total,row,errmsg,errcode,...root}
  },
  error => {

  }
);

let refreshPromise = null,
  // token过期请求数量
  exprReqNum = 0;
function refreshToken() {
  let post = {
    refresh_token: getRefreshToken(),
  }
  if (!refreshPromise || !exprReqNum){
    refreshPromise = new Promise((resolve, reject )=>{
      if (!post.refresh_token){
        console.log(post);
        exprReqNum = 0;
        //重新登录操作....
        ElMessage({
          message: '登录过期，请重新登录',
          type: 'error',
          // showClose: true,
          // offset: 50
          duration: 1500,
          onClose: () => {

            router.push('/login')
          }
        });
        return
      }
      //调用刷新token接口
      setTimeout(res => {
        //刷新成功
        if (res){
          store.dispatch('login',res);
          resolve();
        }
        //失败，重新登录...
        ElMessage({
          message: '登录过期，请重新登录',
          type: 'error',
          duration: 1500,
          onClose: () => {
            store.dispatch('logout');
            router.push('/login')
          }
        });

      },1000)
    })
  }
  exprReqNum++
  return refreshPromise
}

// 重新请求函数
function reRequest(config) {
  return new Promise((resolve, reject) =>{
    request(config).then(res => {
      resolve()
    })
  })


}

/**
 * get请求
 * @param url
 * @param data
 * @return {Promise<any>}
 */
export const get = (url,data)=>{
  return new Promise((resolve,reject ) => {
    if (data) {
      let keys = Object.keys(data);
      let arr = keys.map(item => {
        return item + '=' + data[item]
      });
      url = keys.length ? url + '?' + arr.join('&') : url;
    }
    request.get(url).then(res => {
      resolve(res)
    }, err => {
    })
  })
}
/**
 * post 请求
 * @param url
 * @param data
 * @return {Promise<any>}
 */
export const post = (url,data)=>{
  return new Promise((resolve,reject ) => {
    request.post(url, data).then(res => {
      console.log(res);
      resolve(res);
    }, err => {
    })
  })
}
/**
 * put请求
 * @param url
 * @param data
 * @return {Promise<any>}
 */
export const put = (url,data)=>{
  return new Promise((resolve,reject ) => {
    request.put(url, data).then(res => {
      resolve(res)
    }, err => {
      console.log(err);
    })
  })
}
/**
 * patch请求
 * @param url
 * @param data
 * @return {Promise<any>}
 */
export const patch = (url,data)=>{
  return new Promise((resolve,reject ) => {
    request.patch(url, data).then(res => {
      resolve(res)
    }, err => {
    })
  })
}

/**
 * 删除请求
 * @param url
 * @param data
 * @return {Promise<any>}
 */
export const del = (url,data)=>{
  return new Promise((resolve,reject ) => {
    /*if (data) {
      let keys = Object.keys(data);
      let arr = keys.map(item => item + '=' + data[item]);
      url = url + '?' + arr.join('&')
    }*/
    request.delete(url,{data}).then(res => {
      resolve(res)
    }, err => {
    })
  })
}

export const getFile = (url,data) => {
  return new Promise((resolve,reject ) => {
    if (data) {
      let keys = Object.keys(data);
      let arr = keys.map(item => {
        return item + '=' + data[item]
      });
      url = keys.length ? url + '?' + arr.join('&') : url;
    }
    request({
      url,responseType: 'blob'
    }).then(res => {
      resolve(res)
    }, err => {
    })
  })
}

export default request;
